import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, Input, Modal, Switch, Tree, TreeSelect, message, Space, Dropdown, InputRef, AutoComplete } from 'antd';
import { addDepartment, addUser, delDepartment, deleteUser, deleteUserList, editDepartment, editUser, getAcountList, getAllPositionList, getDepartTree, getPositionList, toggleAccount } from '@/services/demo/UserController';
import "./index.less";
import { ActionType, ProCard, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { AccountCode } from "@/../../code";
import AuthButton from "@/components/AuthButton";
import useResizeObserver from '@/hooks';
interface DepartItem {
  title: string,
  parentId: string,
  id: string,
  children: DepartItem[];
}
interface OptionType {
  label: string,
  key: string;
  code?: string;
}
const items: OptionType[] = [
  {
    label: '编辑',
    key: '1',
    code: AccountCode["BTN_MENU_EDIT"]
  },
  {
    label: '添加类别',
    key: '2',
    code: AccountCode["BTN_ADD_MENU_CLASSIFY"]
  },
  {
    label: '添加子类别',
    key: '3',
    code: AccountCode["BTN_ADD_MENU_CHILD_CLASSIFY"]
  },
  {
    label: '删除',
    key: '4',
    code: AccountCode["BTN_MENU_DEL"]
  },
];

export default function Page() {
  const myRef = useRef(null);
  const [positionOptions, setPositionOptions] = useState<{ value: string; }[]>([]);
  const [optionType, setOptionType] = useState<OptionType>({ key: "", label: "" });
  const [menuLoading, setMenuLoading] = useState(true);
  const [selectedTreeKeys, setSelectedTreeKeys] = useState<React.Key[]>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [model, contextHolder] = Modal.useModal();
  const tableRef = useRef<ActionType>();
  const inputRef = useRef<InputRef | null>(null);
  const [form] = Form.useForm();
  const [treeForm] = Form.useForm();
  const [tableParams, setTableParams] = useState<{ departId?: string, nickName?: string; }>({});
  const [departmentData, setDepatmentData] = useState([]);
  const [departmentValue, setDepartmentValue] = useState<string>();
  const [modalType, setModalType] = useState("新增");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isOptionModalOpen, setIsOptionModalOpen] = useState(false);
  const { initialState: { elements } } = useModel('@@initialState') as any;
  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '姓名',
      dataIndex: 'nickName',
      search: true
    },
    {
      title: '所属部门',
      dataIndex: 'departName',
      search: false,
      ellipsis: true,
      tooltip: ""
    },
    {
      title: '工号',
      dataIndex: 'jobNumber',
      search: false
    },
    {
      title: '岗位名称',
      dataIndex: 'position',
      search: false,
      ellipsis: true,
      tooltip: ""
    },
    {
      title: '邮箱地址',
      dataIndex: 'mail',
      search: false
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
      search: false
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: false,
      render: (text: number, row: { id: string; }) => <Switch disabled={!elements.includes(AccountCode['BTN_STATUS'])} onChange={() => toggleAccount(row.id)
      } defaultChecked={Boolean(text)} />
    },
    {
      title: '操作',
      fixed: 'right',
      search: false,
      render: (user: API.AddUser) => {

        return [
          <Button key="detail" size='small' type='link' onClick={() => accountDetail(user)}>详情</Button>,
          <AuthButton key="edit" size='small' type='link' permission={AccountCode['BTN_EDIT']} onClick={() => accountEdit(user)}>编辑</AuthButton>,
          <AuthButton key="delete" size='small' type='link' danger permission={AccountCode['BTN_DEL']} onClick={() => accountDelete(Number(user.id))}>删除</AuthButton>
        ];
      },
    },
  ];

  useResizeObserver(document.querySelector(".ant-table-tbody") as HTMLElement, contentRect => {
    console.log("vvvvvvvvvvv", contentRect);

  })
  useEffect(() => {
    reloadDepartmentTree();

    getAllPositionList().then(res => {
      if (res.success) {
        const options = res.result.map((data: { postName: string; }) => ({ value: data.postName }));
        setPositionOptions(options);
      }
    });
  }, []);
  const selectChange = (keys: React.Key[]) => {
    setSelectedRowKeys(keys);
  };
  const onFinish = async () => {
    let data;
    let text;
    if (modalType == "新增") {
      const findItem = positionOptions.find(option => option.value == form.getFieldValue("position"));

      if (!findItem) {
        return message.error("岗位不存在，请重新输入");
      }
      const mail = form.getFieldValue("mail");
      !mail && form.setFieldValue("password", mail);
      data = await addUser(form.getFieldsValue());
      text = "新增账户成功";
    } else if (modalType == "编辑") {
      data = await editUser(form.getFieldsValue());
      text = "编辑账户成功";
    }
    const { success, appMesg } = data;
    if (success) {
      (!tableParams.departId || (form.getFieldValue("departId") == tableParams.departId)) && tableRef.current?.reload();
      setIsModalOpen(false);
      message.success(text);
    } else {
      message.error(appMesg);
    }
  };

  const reloadDepartmentTree = () => {
    getDepartTree().then(res => {
      if (res.success) {
        setDepatmentData(res.result);
        setMenuLoading(false);
      }
    });
  };

  const handleDepartment = (newValue: string) => {
    setDepartmentValue(newValue);

  };
  const onMenuSelect = (ids: React.Key[]) => {
    setSelectedTreeKeys(ids);
    const deepTableParams = JSON.parse(JSON.stringify(tableParams));
    deepTableParams.departId = ids[0];
    setTableParams(deepTableParams);
  };
  const handleSubmit = () => {
    form.submit();
  };

  const accountAdd = () => {
    setIsModalOpen(true);
    setModalType("新增");
    form.resetFields();
  };
  const accountEdit = (user: API.AddUser) => {
    setIsModalOpen(true);
    form.setFieldsValue(user);
    setModalType("编辑");
  };
  const accountDetail = (user: API.AddUser) => {
    setIsModalOpen(true);
    form.setFieldsValue(user);
    setModalType("详情");
  };
  const delAccountList = () => {
    if (selectedRowKeys.length) {
      deleteUserList(selectedRowKeys).then(res => {
        if (res.success) {
          message.success("批量删除成功");
          tableRef.current?.reload();
        }
      });
    } else {
      message.warning("请选中要删除的角色列表");
    }
  };
  const accountDelete = async (id: number) => {

    const confirmed = await model.confirm({ content: "确定删除?" });
    if (confirmed) {
      deleteUser(id).then(res => {
        if (res.success) {
          message.success("删除成功");
          tableRef.current?.reload();
        }
      });
    }
  };

  const menuClick = async (e: any, dataNode: DepartItem) => {
    e.domEvent.stopPropagation();

    if (e.key === "4") {
      const confirmed = await model.confirm({ content: dataNode.title + " -> " + "确定删除?" });

      if (confirmed) {
        delDepartment(dataNode.id).then(res => {

          if (res.success) {
            message.success("删除成功");
            reloadDepartmentTree();
          }
        });
      }
    } else {
      setIsOptionModalOpen(true);
      setOptionType({ label: dataNode.title + " -> " + (items![e.key - 1] as any).label, key: e.key });

      ["2", "3"].includes(e.key) && treeForm.resetFields();
      e.key === "1" && treeForm.setFieldValue("deptName", dataNode.title);
      treeForm.setFieldValue("parentId", e.key === "2" ? dataNode.parentId : dataNode.id);
    }
  };
  useEffect(() => {
    if (isOptionModalOpen) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 0);
    }
  }, [isOptionModalOpen]);

  const onTreeFinished = async () => {
    console.log(treeForm.getFieldsValue(), optionType);
    const deepData = treeForm.getFieldsValue();
    const findItem = items?.find(item => item?.key === optionType.key);
    if (!findItem) return;
    let data;
    if (["2", "3"].includes(optionType.key)) {
      data = await addDepartment(deepData);
    } else {

      deepData.id = deepData.parentId;
      delete deepData.parentId;
      console.log(deepData);

      data = await editDepartment(deepData);
    }

    if (data.success) {
      message.success(findItem.label + "成功");
      reloadDepartmentTree();
      if (findItem.key === "1" && tableParams.departId === deepData.id) {
        tableRef.current?.reload();
      }
    } else {
      message.error(findItem.label + "是啊比");
    }

    setIsOptionModalOpen(false);
  };

  const selectFirst = (e: React.KeyboardEvent) => {
    e.stopPropagation();
    if (e.code == "Enter") {
      form.setFieldValue("position", positionOptions[0].value);
    }

  };
  const confirmOpen = async (e: boolean) => {
    const confirmed = await model.confirm({ content: "是否确定开启？" });
    form.setFieldValue("status", Number(confirmed ? e : !e));
  }

  const resetPassword = () => {
    form.setFieldValue("password", form.getFieldValue("mail"))
  }
  return (
    <div>
      <ProCard split="vertical" style={{ height: "calc(100vh - 176px)" }}>
        <ProCard headerBordered loading={menuLoading} colSpan="20%" style={{ height: "100%", overflowY: "auto" }}>
          <Tree
            onSelect={onMenuSelect}
            fieldNames={{ title: "title", key: "id", children: "children" }}
            treeData={departmentData}
            selectedKeys={selectedTreeKeys}
            titleRender={(dataNode: any) => <Dropdown menu={{ items: items.filter(item => elements.includes(item.code)), onClick: (e) => menuClick(e, dataNode) }} trigger={['contextMenu']}><div>{dataNode.title}</div></Dropdown>
            }
          />
        </ProCard>
        <ProCard headerBordered colSpan="80%" style={{ height: "100%", overflowY: "auto" }}>
          <ProTable
            search={{ labelWidth: 'auto' }}
            options={false}
            headerTitle={<Space style={{ marginBottom: "20px" }}>
              <AuthButton type='primary' permission={AccountCode['BTN_ADD']} onClick={accountAdd}>新增</AuthButton>
              <AuthButton permission={AccountCode['BTN_ALL_DEL']} onClick={delAccountList}>批量删除</AuthButton>
            </Space>}
            actionRef={tableRef}
            cardBordered
            params={tableParams}
            request={async (params) => {
              const { current, pageSize, departId, nickName } = params;
              const { success, result: { datas, total } } = await getAcountList({ page: current!, size: pageSize!, param: { departId, nickName } });
              return { data: datas, total, success };

            }}
            columns={columns}
            rowKey="id"
            rowSelection={{ selectedRowKeys, onChange: selectChange }}
          />
        </ProCard>
      </ProCard>


      <Modal title={optionType.label} maskClosable={false} open={isOptionModalOpen} onOk={() => treeForm.submit()} onCancel={() => setIsOptionModalOpen(false)} okText="提交">
        <Form form={treeForm} onFinish={onTreeFinished}>
          <Form.Item label="parentId"
            name="parentId"
            hidden
            rules={[{ required: true, message: '无父节点id' }]}>
            <Input allowClear placeholder='父节点id' />
          </Form.Item>
          <Form.Item label="部门名称"
            name="deptName"
            rules={[{ required: true, message: '请输入部门名称' }]}>
            <Input ref={inputRef} showCount maxLength={20} allowClear placeholder='请输入部门名称' />
          </Form.Item>
        </Form>
      </Modal>

      <Modal width="1200px" footer={(dom: React.ReactNode) => modalType == "详情" ? null : dom} className='account_modal' title={`账号管理 - ${modalType}`} maskClosable={false} open={isModalOpen} onOk={handleSubmit} onCancel={() => setIsModalOpen(false)} okText="提交" >
        <Form size='large' labelCol={{ span: 4 }} form={form} disabled={modalType === "详情"} initialValues={{ status: 1 }} onFinish={onFinish}>
          <Form.Item
            name="id"
            hidden
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="nickName"
            rules={[{ required: true, message: 'Please input name' }]}
          >
            <Input allowClear placeholder='请输入姓名' maxLength={30} showCount />
          </Form.Item>
          <Form.Item
            label="所属部门"
            name="departId"
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <TreeSelect
              allowClear
              showSearch
              value={departmentValue}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择所属部门"
              treeDefaultExpandAll
              onChange={handleDepartment}
              treeData={departmentData}
              fieldNames={{ label: "title", value: "id", children: "children" }}
            />
          </Form.Item>
          <Form.Item label="工号"
            name="jobNumber"
            rules={[{ required: true, message: '请输入唯一工号' }, { pattern: /^(TC|TCF)\d{4}$/, message: "格式错误" }]}>
            <Input allowClear placeholder='请输入唯一工号' maxLength={7} showCount />
          </Form.Item>

          <Form.Item label="岗位"
            name="position"
            rules={[{ required: true, message: '请输入岗位名称' }]}
          >
            <AutoComplete
              placeholder="请输入岗位名称"
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              filterOption={(inputValue, option: any) =>
                option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
              }
              options={positionOptions}
              onKeyUp={selectFirst}
            >
              <Input.Search />
            </AutoComplete>
          </Form.Item>
          <Form.Item
            label="邮箱地址"
            name="mail"
            rules={[{ required: true, message: '请输入唯一邮箱地址' }, { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: "邮箱格式错误" }]}
          >
            <Input allowClear placeholder='请输入唯一邮箱地址' />
          </Form.Item>
          <Form.Item
            label="手机号码"
            name="phone"
            rules={[{ required: true, message: '请输入唯一手机号码' }, { pattern: /^1\d{10}$/, message: "手机号格式错误" }]}
          >
            <Input allowClear placeholder='请输入唯一手机号码' />
          </Form.Item>
          <Form.Item
            label="启用"
            name="status"
          >
            <Switch onChange={confirmOpen} />
          </Form.Item>

          <Form.Item
            label="密码设置"
            hidden={modalType != "编辑"}
          >
            <Form.Item hidden name="password">
              <Input placeholder='请输入密码' />
            </Form.Item>
            <Button type='primary' onClick={resetPassword} >重置密码</Button>
          </Form.Item>

          <Form.Item
            label="备注"
            name="remark"
            style={{ width: "100%" }}
            labelCol={{ span: 2 }}
          >
            <Input.TextArea placeholder='请输入备注' allowClear autoSize={{ minRows: 3 }} showCount maxLength={500} />
          </Form.Item>
        </Form>
      </Modal>
      {contextHolder}
    </div>
  );
}
